package br.unifor.cadeventos.dao;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;

public class ConnectionFactory {

	private static Logger logger = Logger.getLogger(ConnectionFactory.class);
	private static BoneCP pool;
	private static final ConnectionFactory connFactory = new ConnectionFactory();
	
	private ConnectionFactory() {
		try {
			BoneCPConfig config = new BoneCPConfig();
			config.setJdbcUrl("jdbc:postgresql://localhost:5432/eventos");
			config.setUser("postgres");
			config.setPassword("postgres");
			config.setMinConnectionsPerPartition(3);
			config.setMaxConnectionsPerPartition(50);
			config.setPartitionCount(1);
			pool = new BoneCP(config);
			logger.info("Construtor: Conexoes: "+pool.getTotalCreatedConnections()
					+"Conexao livre: "+pool.getTotalFree()
					+"Conexao ocupada: "+pool.getTotalLeased());
		} catch (SQLException e) {
			logger.fatal("Não foi possível criar o pool de conexões!", e);
		}
	}
	
	public static ConnectionFactory getInstance(){
		return connFactory;
	}

	public static Connection getConnection() {
		Connection conn = null;
		try {
			conn = pool.getConnection();
			logger.info("getConnection: Conexoes: "+pool.getTotalCreatedConnections()
					+" Conexao livre: "+pool.getTotalFree()
					+" Conexao ocupada: "+pool.getTotalLeased());
		} catch (SQLException e) {
			logger.fatal("Não foi possível conectar com o banco de dados!", e);
		}

		return conn;
	}
	
	public static void cleanConnection(Connection conn) throws SQLException{
		logger.info("Clean(Antes): Conexoes: "+pool.getTotalCreatedConnections()
				+" Conexao livre: "+pool.getTotalFree()
				+" Conexao ocupada: "+pool.getTotalLeased());
		conn.close();
		logger.info("Clean(Depois): Conexoes: "+pool.getTotalCreatedConnections()
				+" Conexao livre: "+pool.getTotalFree()
				+" Conexao ocupada: "+pool.getTotalLeased());
	}
	
	public static void shutdownConnectionPool(){
		if(pool != null) {
			logger.info("Shutdown(Antes): Conexoes: "+pool.getTotalCreatedConnections()
					+" Conexao livre: "+pool.getTotalFree()
					+" Conexao ocupada: "+pool.getTotalLeased());
			pool.shutdown();
			logger.info("Shutdown(Depois): Conexoes: "+pool.getTotalCreatedConnections()
					+" Conexao livre: "+pool.getTotalFree()
					+" Conexao ocupada: "+pool.getTotalLeased());
		}
	}
}
